<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* div {
            height: 200px;
            width: 200px;
            margin: 1px;
            border: 1px solid black;
        } */
    </style>
</head>

<body>
    <input type="text" placeholder="请输入">
    <button>发送</button>
    <!-- 显示内容 -->
    <div></div>
    <script>
        let input = document.querySelector('input')
        let button = document.querySelector('button')
        let div = document.querySelector('div')
        // 创建一个websocket
        let socket = new WebSocket('ws://localhost:3000')
        // 监听socket 链接事件
        socket.addEventListener('open', () => {
            div.innerHTML = '链接成功'
        })

        // 给websocket 发送消息
        button.addEventListener('click', () => {
            let value = input.value
            socket.send(value)
        })

        socket.addEventListener('message', (msg) => {
            let dv = document.createElement('div')
            div.append(dv)
            dv.innerHTML += msg.data
        })

        socket.addEventListener('close', () => {
            console.log('服务断开')
        })
    </script>
</body>

</html>